﻿using BLL.ASRepair;
using BLL.Base;
using BLL.App;
using BLL.custom;
using CommandService;
using Entity;
using Entity.DbEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.SS.Formula.Functions;
using Entity.FrameEntity;
using NPOI;
using System.Threading;
using Tools;
using System.Reflection;

namespace BLL
{
    /// <summary>
    /// 接口服务逻辑处理层
    /// </summary>
    public class ServiceBLL : PubMethod
    {
        HttpAgreement http;
        Commands cmd;
        LoginInfo userLogin;
        Tools.TxtLogHelper txt;
        ReturnResult rsl;
        SystemBLL sysBLL;
        CuDbHelper cuHelper;
        BarBLL barBLL;
        ASRepairBLL asrepair;
        StringBuilder sb = new StringBuilder();
        public ServiceBLL()
        {
            http = new HttpAgreement();
            cmd = new Commands();
            userLogin = new LoginInfo();
            txt = new Tools.TxtLogHelper();
            sysBLL = new SystemBLL();
            cuHelper = new CuDbHelper();
            barBLL = new BarBLL();
            asrepair = new ASRepairBLL();
        }

        /// <summary>
        /// 加载扫描临时数据表
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult loadScanTempDatas(string jsonStr)
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传递参数不允许为空";
                    return rsl;
                }
                var obj = JsonConvert.DeserializeObject<JObject>(jsonStr);
                sb = new StringBuilder();
                sb.Append("select * from V_Bar_TempData where  operateType='" + obj["dataType"] + "'");
                if (!string.IsNullOrWhiteSpace(obj["tempCode"].ToString()))
                {
                    sb.Append(" and tempCode='" + obj["tempCode"] + "'");
                }
                var data = cmd.GetDataTable(sb.ToString());
                var dic = new Dictionary<string, object>();
                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(data);
                txt.AddLogMsg(string.Format("MloadTempData方法，返回参数：{0}", JsonConvert.SerializeObject(rsl.Data)));
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 验证条码是否已经扫描(出入库)
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult CheckRepeatTempBar(string jsonStr)
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传递参数有误";
                    return rsl;
                }
                var obj = JsonConvert.DeserializeObject<JObject>(jsonStr);
                sb = new StringBuilder();
                sb.Append("select top 1 barCode from bar_TempScanData_info where 1=1");
                if (obj.Property("tempCode") != null)
                {
                    sb.Append(" and tempCode='" + obj["tempCode"].ToString() + "'  ");
                }
                sb.Append(" and barCode='" + obj["barCode"].ToString() + "'");
                if (!string.IsNullOrWhiteSpace(obj["operateType"].ToString()))
                {
                    sb.Append(" and operateType='" + obj["operateType"].ToString() + "'");
                }
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Result = true;
                //如果有数据就为1
                if (table.Rows.Count > 0)
                {
                    rsl.Data = 1;
                }
                else
                {//没有数据就显示为0
                    rsl.Data = 0;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取临时表中扫描的当前的条码信息
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult getScanBarCode(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                DataTable dt = new DataTable();
                string helperCode = string.Empty;
                string helperName = string.Empty;
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                Dictionary<string, object> dic = new Dictionary<string, object>();
                List<OperateModel> sqlList = new List<OperateModel>();
                sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "参数不允许为空";
                    return rsl;
                }
                txt.AddLogMsg("getScanBarCode方法参数：" + jsonStr);
                JObject json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                sb.Clear();
                sb.Append("select barCode,proWeight as weight,barStatus , count(*) number ");
                sb.Append(" from bar_ProductBarCode_info ");
                sb.Append("where barCode='" + json["barCode"].ToString() + "' ");
                sb.Append("group by barCode,proWeight,barStatus ");
                dt = cmd.GetDataTable(sb.ToString());
               
                if (dt != null && dt.Rows.Count > 0)
                {
                    var scanList = cmd.TableToDictionary(dt);
                    Dictionary<string, string> temdic = new Dictionary<string, string>();
                    temdic.Add("barCode", "条码编码");
                    temdic.Add("number", "数量");
                    temdic.Add("weight", "重量");

                    scanList.Insert(0, temdic);
                    dic.Add("scanList", scanList);
                    list.Add(dic);
                    rsl.Data = list;
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "没有该扫描条码的数据";
                    rsl.Result = false;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       
        /// <summary>
        /// 将数据转为U8材料出库单数据
        /// </summary>
        /// <param name="data"></param>
        /// <param name="dataList"></param>
        private void getTempDataList(List<Dictionary<string, string>> data, ref List<object> dataList)
        {
            foreach (var gr in data)
            {
                var typeCode = "";
                var deptCode = "";
                typeCode = cmd.getParam("typeCode")[0].parValue;
                deptCode = cmd.getParam("deptCode")[0].parValue;
                //var tempDic = new Dictionary<string, string>();
                var tempDic = new
                {
                    wareHouse = gr["wareHouse"].ToString(),
                    typeCode = typeCode,
                    deptCode = deptCode,
                    proCode = gr["proCode"].ToString(),
                    quantity = gr["iQuantity"].ToString(),
                    number = gr["number"].ToString(),
                    weight = gr["c_gongjin"].ToString(),
                    customer = gr["cu_outCompany"].ToString(),
                    xinghao = gr["c_xinghao"].ToString(),
                    meter = gr["c_mishu"].ToString(),
                    xilie = gr["c_xilie"].ToString(),
                    batch = gr["c_plBatch"].ToString(),
                    goodsPosition = gr["warePosition"].ToString(),
                    isBlue = gr["isBlue"].ToString(),
                };
                dataList.Add(tempDic);
            }
        }
     
        /// <summary>
        /// 获取临时表中扫描的当前的条码信息
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult getAssembelScanBarCode(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                DataTable dt = new DataTable();
                string helperCode = string.Empty;
                string helperName = string.Empty;
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                Dictionary<string, object> dic = new Dictionary<string, object>();
                List<OperateModel> sqlList = new List<OperateModel>();
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "参数不允许为空";
                    return rsl;
                }
                txt.AddLogMsg("getScanBarCode方法参数：" + jsonStr);
                JObject json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                if (json.Property("momNum") != null && !string.IsNullOrWhiteSpace(json["momNum"].ToString()))
                {
                    var barCode = string.Empty;//条码编码
                    var temBarCode = json["barCode"].ToString();
                    for (int i = 0; i < Convert.ToInt32(json["momNum"].ToString()); i++)
                    {
                        var str = "";
                        for (int it = 0; it < temBarCode.Length; it++)
                        {
                            var s = temBarCode[it].ToString();
                            if (!s.Equals("0"))
                            {
                                break;
                            }
                            else
                            {
                                str += temBarCode[it];
                            }
                        }
                        barCode = str + Convert.ToString(Convert.ToInt64(temBarCode) + i);

                        sb.Clear();
                        sb.Append("select bar.barCode,inv.proCode,inv.proName,inv.spec,inv.cu_ckdgg,inv.cu_jssm, ");
                        sb.Append(" bar.types,bar.barStatus,bar.U8relationCode from bar_ProductBarCode_info bar ");
                        sb.Append("inner join fun_Inventory_Info inv on bar.proCode = inv.proCode ");
                        sb.Append("where bar.barCode='" + barCode + "'");
                        dt = cmd.GetDataTable(sb.ToString());

                        if (dt.Rows.Count > 0)
                        {
                            #region 判断组装操作时数据的类型

                            if (json.Property("operateType") != null)
                            {
                                if (json["operateType"].ToString().Equals("03"))
                                {
                                    //半成品只能通过半成品组装
                                    if (dt.Rows[0]["types"].Equals("001") && !json["assemblyType"].ToString().Equals("pabc"))
                                    {
                                        rsl.Result = false;
                                        rsl.Message = "此条码为半成品只能通过半成品组装";
                                        return rsl;
                                    }

                                    if (!dt.Rows[0]["types"].Equals("000") && !dt.Rows[0]["types"].Equals("001") && !dt.Rows[0]["types"].Equals("002"))
                                    {
                                        rsl.Result = false;
                                        rsl.Message = "母件不能为原材料";
                                        return rsl;
                                    }
                                    if (!json["assemblyType"].ToString().Equals("pazp"))
                                    {
                                        //如果条码状态为返工
                                        if (dt.Rows[0]["barStatus"].ToString().Equals("need-rework"))
                                        {
                                            DbProductBar barInfor = new DbProductBar();
                                            barInfor.barCode = barCode;
                                            barInfor.barStatus = "need-assemble";
                                            OperateModel oper = new OperateModel();
                                            oper.Data = barInfor;
                                            oper.Types = OperateModel.OperateType.Edit;
                                            oper.Conditions = "barCode";
                                            sqlList.Add(oper);
                                        }
                                        else
                                        {
                                            if (!dt.Rows[0]["barStatus"].ToString().Equals("need-assemble"))//是否为待组装条码
                                            {
                                                rsl.Result = false;
                                                rsl.Message = "此条码为" + new AppBLL().getBarStatus(dt.Rows[0]["barStatus"].ToString()) + "状态不是待组装";
                                                return rsl;
                                            }
                                        }
                                    }
                                    //不需要子件组装
                                    if (!string.IsNullOrWhiteSpace(json["isNeedChild"].ToString()) && json["isNeedChild"].ToString().Equals("0"))
                                    {
                                        #region 母件被占用
                                        var db = JsonConvert.DeserializeObject<DbTempAssemble>(jsonStr);
                                        sb.Clear();
                                        sb.Append("select temp.*,u.userName from bar_TempAssemble_info temp  ");
                                        sb.Append(" left join sys_users_info u on temp.createuser=u.userCode");
                                        sb.Append(" where temp.momBar='" + barCode + "' ");
                                        var tempTable = cmd.GetDataTable(sb.ToString());
                                        if (tempTable.Rows.Count > 0)
                                        {
                                            //if (tempTable.Rows[0]["createuser"].ToString() != db.createuser)
                                            //{
                                            //    rsl.Result = false;
                                            //    rsl.Message = "该母件已被" + tempTable.Rows[0]["userName"].ToString() + "占用";
                                            //    return rsl;
                                            //}
                                        }

                                        DbTempAssemble tem = new DbTempAssemble();
                                        tem.momBar = barCode;
                                        var tempDt = cmd.GetDataByObject<DbTempAssemble>(tem);
                                        if (tempDt.Count > 0)
                                        {
                                            rsl.Result = false;
                                            rsl.Message = "该条码已扫描";
                                            return rsl;
                                        }
                                        #endregion
                                        #region 获取协助人员
                                        //获取协助人员
                                        List<Dictionary<String, String>> helperList = null;
                                        if (json.Property("assistantList") != null)
                                        {
                                            helperList = JsonConvert.DeserializeObject<List<Dictionary<String, String>>>(json["assistantList"].ToString());
                                            if (helperList != null && helperList.Count > 0)
                                            {
                                                foreach (var item in helperList)
                                                {
                                                    helperCode += item["code"].ToString() + ",";
                                                    helperName += item["name"].ToString() + ",";
                                                }
                                            }
                                        }
                                        #endregion
                                        if (!dt.Rows[0]["types"].Equals("000") && !dt.Rows[0]["types"].Equals("001") && !dt.Rows[0]["types"].Equals("002"))
                                        {
                                            rsl.Result = false;
                                            rsl.Message = "母件不能为原材料";
                                            return rsl;
                                        }
                                        if (!dt.Rows[0]["barStatus"].ToString().Equals("need-assemble"))
                                        {
                                            rsl.Result = false;
                                            rsl.Message = "扫描的母件为" + new AppBLL().getBarStatus(dt.Rows[0]["barStatus"].ToString()) + "状态不是待组装";
                                            return rsl;
                                        }
                                        DbTempAssemble temp = new DbTempAssemble();
                                        temp.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                                        temp.momBar = barCode;
                                        temp.number = "0";//不需要子件
                                        temp.types = json["assemblyType"].ToString();
                                        temp.createtime = getNow();
                                        temp.createuser = db.createuser;
                                        temp.dType = db.dType;
                                        temp.relationOrder = dt.Rows[0]["U8relationCode"].ToString();
                                        temp.helperCode = helperCode.TrimEnd(',');
                                        temp.helperName = helperName.TrimEnd(',');
                                        OperateModel opera = new OperateModel();
                                        opera.Data = temp;
                                        opera.Types = OperateModel.OperateType.Add;
                                        sqlList.Add(opera);
                                    }
                                }
                            }
                            #endregion
                        }
                    }

                    if (sqlList.Count > 0)
                    {
                        rsl = cmd.MoreUpdate(sqlList);
                        if (!rsl.Result)
                        {
                            return rsl;
                        }
                    }
                    var scanList = cmd.TableToDictionary(dt);
                    Dictionary<string, string> temdic = new Dictionary<string, string>();
                    temdic.Add("barCode", "SN码");
                    temdic.Add("proCode", "存货编码");
                    temdic.Add("proName", "存货名称");
                    temdic.Add("spec", "存货类型");
                    temdic.Add("cu_ckdgg", "出库单规格");
                    temdic.Add("cu_jssm", "解释说明");
                    scanList.Insert(0, temdic);
                    dic.Add("scanList", scanList);
                    list.Add(dic);
                    rsl.Data = list;
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "没有该扫描条码的数据";
                    rsl.Result = false;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 添加扫码记录
        /// </summary>
        /// <param name="jsonStr">json串</param>
        /// <param name="number">重量</param>
        /// <returns></returns>
        public ReturnResult AddScanTempRecord(string number, string jsonStr, ref List<OperateModel> operList, string iscar = null)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                DbTempScanData scan;
                //List<OperateModel> operList = new List<OperateModel>();
                OperateModel oper;
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Result = false;
                    rsl.Message = "参数不允许为空";
                    return rsl;
                }
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                var scanTable = new DataTable();
                #region 防错验证
                if (json["operateType"].ToString().Equals("01") || json["operateType"].ToString().Equals("02"))
                {
                    if (string.IsNullOrWhiteSpace(json["tempCode"].ToString()))
                    {
                        rsl.Result = false;
                        rsl.Message = "临时编码不允许为空";
                        return rsl;
                    }

                    #endregion
                    sb.Append("select barCode,createuser from  bar_TempScanData_info ");
                    sb.Append("where tempCode='" + json["tempCode"].ToString() + "'");
                    scanTable = cmd.GetDataTable(sb.ToString());//获取扫描单下的所有扫描记录    
                }
                if (isBoxCode(json["barCode"].ToString()))
                {
                    #region 扫描码为箱码
                    sb.Clear();
                    sb.Append("select barCode from bar_ProductBarCode_info where ");
                    sb.Append("boxCode='" + json["barCode"].ToString() + "'");
                    var bars = cmd.GetDataTable(sb.ToString());//获取箱码下所有的条码信息
                    if (bars.Rows.Count < 1)
                    {
                        rsl.Message = "空箱不允许扫描";
                        return rsl;
                    }
                    foreach (DataRow r in bars.Rows)
                    {
                        var dr = scanTable.Select("barCode='" + r["barCode"].ToString() + "'");
                        if (dr.Length < 1)
                        {//判断所属箱码的条码是否被重复扫描，没有记录则添加
                            scan = new DbTempScanData();
                            scan = JsonConvert.DeserializeObject<DbTempScanData>(jsonStr);
                            scan.barCode = r["barCode"].ToString();
                            scan.boxCode = json["barCode"].ToString();
                            scan.inOutType = json["inOutType"].ToString();
                            //scan.targetWareHouse = json["wareHouse"].ToString();
                            scan.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                            oper = new OperateModel();
                            oper.Data = scan;
                            oper.Types = OperateModel.OperateType.Add;
                            operList.Add(oper);
                        }
                    }
                    #endregion
                }
                else
                {
                    #region 非箱码
                    if (string.IsNullOrWhiteSpace(iscar))
                    {
                        #region 非车码
                        sb.Clear();
                        sb.Append("select barCode,warePosition from bar_ProductBarCode_info where 1=1 ");
                        sb.Append(" and barCode='" + json["barCode"].ToString() + "' ");
                        var barDt = cmd.GetDataTable(sb.ToString());
                        //var barCode = json["barCode"].ToString();//条码编码
                        scan = new DbTempScanData();
                        scan = JsonConvert.DeserializeObject<DbTempScanData>(jsonStr);
                        scan.barCode = json["barCode"].ToString();
                        //出库时发生货位默认带出条码上的货位(出库时不是红单的操作)
                        if ((json["operateType"].ToString().Equals("02") && !json["isBlue"].ToString().Equals("0")) || json["operateType"].ToString().Equals("03"))
                        {
                            scan.goodsPosition = barDt.Rows[0]["warePosition"].ToString();
                        }
                        //if (json["operateType"].ToString().Equals("02") && json.Property("cu_personCode") != null)
                        //{
                        //    scan.cu_personName = json["proCode"].ToString();//生产订单的存货
                        //}
                        scan.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                        scan.inOutType = json["inOutType"].ToString();
                        scan.iQuantity = "1";//件数
                        scan.number = number;//重量
                        oper = new OperateModel();
                        oper.Data = scan;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                        rsl.Result = true;
                        #endregion
                    }
                    else
                    {
                        #region 车码
                        sb.Clear();
                        sb.Append("select * from bar_SheBeiBarCode_info where barCode = '" + json["barCode"].ToString() + "' and status = 'Y' and barType = 'ca' ");
                        var barDt = cmd.GetDataTable(sb.ToString());
                        scan = new DbTempScanData();
                        scan = JsonConvert.DeserializeObject<DbTempScanData>(jsonStr);
                        scan.barCode = json["barCode"].ToString();
                        scan.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                        scan.inOutType = json["inOutType"].ToString();
                        scan.iQuantity = "1";//件数
                        scan.number = number;//重量
                        oper = new OperateModel();
                        oper.Data = scan;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                        rsl.Result = true;
                        #endregion
                    }

                    #endregion
                }
            }
            catch (Exception ex)
            {
                rsl.Result = false;
                rsl.Message = ex.Message;
                return rsl;
            }
            return rsl;
        }

        /// <summary>
        /// 验证扫描条码是否有效(应用范围：移动端)
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult CheckBarCode(string barCode, Dictionary<string, string> tempDic)
        {
            rsl = new ReturnResult();
            try
            {
                var inOutType = tempDic["inOutType"].ToString();
                var baseCode = tempDic["baseCode"].ToString();
                StringBuilder sb = new StringBuilder();

                sb.Append("select distinct * from V_BarCode_Info ");//非箱码
                sb.Append("where barCode='" + barCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "此码系统不存在";
                    rsl.Result = false;
                }
            }
            catch (Exception ex)
            {
                rsl.Result = false;
                rsl.Message = ex.Message;
            }
            return rsl;
        }



        /// <summary>
        /// 删除临时数据
        /// </summary>
        /// <param name="table"></param>
        /// <param name="list"></param>
        /// <param name="erridList"></param>
        /// <param name="type"></param>
        private void delteTempCode(DataTable table,ref List<OperateModel> list, string type)
        {
            #region 删除临时数据
            if (table.Rows.Count > 0)
            {
                foreach (DataRow dr in table.Rows)
                {
                    DbTempScanData temp = new DbTempScanData();
                    temp.tempCode = dr["tempCode"].ToString();
                    temp.barCode = dr["barCode"].ToString();
                    temp.inOutType = type;
                    OperateModel oper = new OperateModel();
                    oper.Data = temp;
                    oper.Types = OperateModel.OperateType.Delete;
                    list.Add(oper);
                }
            }
            #endregion
        }

    

        /// <summary>
        /// 出入库记录单主表
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="qList"></param>
        /// <param name="list"></param>
        public void insertMain(Dictionary<string, object> dic, DataTable table,string outOrderCode, ref List<OperateModel> list)
        {
            #region 反写出入库记录的主表
            var type = dic["type"].ToString();
            var mCode = dic["mCode"].ToString();//临时编码
            var baseCode = dic["baseCode"].ToString();//
            DbBarRecordsMain main = new DbBarRecordsMain();
            main.happenDate = table.Rows[0]["happenDate"].ToString();
            main.outOrderCode = outOrderCode;
            main.wareHouse = table.Rows[0]["wareHouse"].ToString();
            main.isBlue = table.Rows[0]["isBlue"].ToString();
            main.createuser = table.Rows[0]["createuser"].ToString();
            main.mType = table.Rows[0]["typeCode"].ToString();
            main.deptCode = table.Rows[0]["operateDept"].ToString();
            main.createtime = getNow();
            main.baseCode = baseCode;
            main.status = "needAudit";
            main.maker = table.Rows[0]["createuser"].ToString();
            main.inOutType = type;
            main.referOrderCode = table.Rows[0]["outOrderCode"].ToString();//关联U8单据号
            main.customCode = table.Rows[0]["customCode"].ToString();
            main.mCode = mCode;//主表的临时码
            main.isForm = "app";//数据来源
            OperateModel oper = new OperateModel();
            oper.Data = main;
            oper.Types = OperateModel.OperateType.Add;
            list.Add(oper);
            txt.AddLogMsg("反写出入库记录主表单据号：" + mCode);
            #endregion
        }
         
        /// <summary>
        /// 出入库记录子表
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="qList"></param>
        /// <param name="list"></param>
        /// <param name="barCodes"></param>
        /// <param name="erridList"></param>
        /// <returns></returns>
        public ReturnResult insertList(Dictionary<string, object> dic, DataTable table, ref List<OperateModel> list, ref string barCodes, List<string> erridList)
        {
            #region 反写出入库单据明细表的数据
            var type = dic["type"].ToString();
            var mCode = dic["mCode"].ToString();//临时编码
            var baseCode = dic["baseCode"].ToString();
            rsl = new ReturnResult();
            foreach (DataRow dr in table.Rows)
            {
                string barCode = dr["barCode"].ToString();
                //改变条码的状态
                rsl = updateBarCodeStatus(barCode, dr, ref list, table, type);
                if (!rsl.Result)
                {
                    return rsl;
                }
                
                StringBuilder sb = new StringBuilder();
                sb.Append("select id,proCode,barCode,barStatus,proWeight ");
                sb.Append("from bar_ProductBarCode_info where barCode='" + barCode + "'");
                var t = cmd.GetDataTable(sb.ToString());
                if (t.Rows.Count > 0)
                {
                    DbBarRecordsList dl = new DbBarRecordsList();
                    dl.barCode = barCode;
                    dl.mCode = mCode;//主表临时编码
                    dl.status = "Y";
                    dl.createuser = dr["createuser"].ToString();
                    var listCount = cmd.GetDataByObject<DbBarRecordsList>(dl).Count;
                    if (listCount <= 0)
                    {
                        var barcode = barCodes.Split(',');
                        if (!barcode.Contains(barCode))
                        {
                            barCodes += barCode + ",";
                            #region list数据
                            dl = new DbBarRecordsList();
                            dl.barCode = barCode;
                            dl.createtime = getNow();
                            dl.mCode = mCode;//主表临时编码
                            dl.num = t.Rows[0]["proWeight"].ToString();
                            dl.inOutType = type;
                            dl.status = "Y";
                            dl.createuser = dr["createuser"].ToString();
                            OperateModel oper = new OperateModel();
                            oper.Data = dl;
                            oper.Types = OperateModel.OperateType.Add;
                            list.Add(oper);
                            #endregion
                        }
                    }
                    rsl.Result = true;
                }
                else
                {
                    rsl.Result = false;
                    rsl.Message = string.Format("标签记录不存在：{0}", barCode);
                }
            }
            #endregion
            return rsl;
        }


        /// <summary>
        /// 改变条码状态
        /// </summary>
        /// <param name="barCode"></param>
        /// <param name="list"></param>
        /// <param name="table"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private ReturnResult updateBarCodeStatus(string barCode, DataRow dr, ref List<OperateModel> list, DataTable table, string type)
        {
            rsl = new ReturnResult();
            OperateModel oper = new OperateModel();
            StringBuilder sb = new StringBuilder();
            sb.Append("select id,proCode,barCode,barStatus,proWeight ");
            sb.Append("from bar_ProductBarCode_info where barCode='" + barCode + "'");
            var t = cmd.GetDataTable(sb.ToString());
            if (t.Rows.Count > 0)
            {
                string status = t.Rows[0]["barStatus"].ToString();
                //改变状态为完成
                var barStatus = string.Empty;//工序状态
                var msg = string.Empty;
                #region 改变条码状态
                DbProductBar barInfo;
                if (table.Rows[0]["operateType"].ToString().ToLower() == "01")
                {
                }
                else if (table.Rows[0]["operateType"].ToString().ToLower() == "02")
                {
                    #region 改变条码状态
                    //改变状态为完成
                    barStatus = string.Empty;//工序状态
                    msg = string.Empty;
                    //获取该条码的下一道工序
                    barStatus = "bar-finish";

                    if (!string.IsNullOrWhiteSpace(barStatus))
                    {
                        barInfo = new DbProductBar();
                        barInfo.Id = int.Parse(t.Rows[0]["Id"].ToString());
                        barInfo.barStatus = barStatus;
                        barInfo.warePosition = "-";
                        barInfo.wareHouse = "-";//出库时 标签所属仓库清空(如考虑数量需要重新更改此处代码)    
                        barInfo.memo = msg;
                        oper = new OperateModel();
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Data = barInfo;
                        oper.Conditions = "Id";
                        list.Add(oper);
                    }
                    #endregion
                }
                else if (table.Rows[0]["operateType"].ToString().ToLower() == "03")
                {
                }
                #endregion
            }
            else
            {
                rsl.Result = false;
                rsl.Message = string.Format("标签记录不存在：{0}", barCode);
                return rsl;
            }
            rsl.Result = true;
            return rsl;
        }

     

     
        /// <summary>
        /// 删除重复数据(出入库)
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult DelCollectRepeat(string jsonStr)
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                var obj = JsonConvert.DeserializeObject<JObject>(jsonStr);
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传递参数有误";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("delete from bar_TempScanData_info where ");
                sb.Append("barCode='" + obj["barCode"].ToString() + "'");
                if (obj.Property("mobType") != null && !string.IsNullOrWhiteSpace(obj["mobType"].ToString()) && obj["mobType"].ToString().Equals("H5"))
                {
                    sb.Append(" and tempCode='" + obj["tempCode"].ToString() + "'");
                }
                rsl = cmd.UpdateSql(sb.ToString());
                if (rsl.Result)
                {
                    var barNumber = 0;
                    #region 获取该临时码中扫描的条码个数
                    sb.Clear();
                    sb.Append("select barCode,createuser from  bar_TempScanData_info ");
                    sb.Append("where tempCode='" + obj["tempCode"].ToString() + "'");
                    var scanTable = cmd.GetDataTable(sb.ToString());//获取扫描单下的所有扫描记录    
                    if (scanTable != null && scanTable.Rows.Count > 0)
                    {
                        barNumber = scanTable.Rows.Count;
                    }
                    var dic = new Dictionary<string, string>();
                    dic["barNumber"] = barNumber.ToString();
                    rsl.Data = dic;
                    #endregion
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }

        /// <summary>
        /// 保存临时数据
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult MSaveTempData(string jsonStr)
        {
            rsl = new ReturnResult();
            var proCodes = string.Empty;
            var tempcode = string.Empty;//临时编码号
            try
            {
                txt.AddLogMsg("MSaveTempData方法，参数数据：" + jsonStr);
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Result = false;
                    rsl.Message = "传递参数有误";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                var obj = JsonConvert.DeserializeObject<JObject>(jsonStr);
                tempcode = obj["tempCode"].ToString();
                #region 根据临时编码获取到临时数据

                if (string.IsNullOrWhiteSpace(tempcode))
                {
                    rsl.Message = "扫描单号不能为空";
                    rsl.Result = false;
                    return rsl;
                }
                sb.Append("select t.*,b.proWeight,b.barStatus,proCode from bar_TempScanData_info t ");
                sb.Append("inner join bar_ProductBarCode_info b on t.barCode=b.barCode ");
                sb.Append("where tempCode='" + tempcode + "' ");
                DataTable teTable = cmd.GetDataTable(sb.ToString());//获取扫描条码

                if (teTable.Rows.Count < 1)
                {
                    rsl.Result = false;
                    rsl.Message = "没有要提交的数据";
                    return rsl;
                }
                #endregion

                txt.AddLogMsg("获取数据：" + teTable.Rows.Count);

                var outOrderCode =teTable.Rows[0]["outOrderCode"].ToString();
                var baseCode = obj["baseCode"].ToString();
                var sdId = "";
                var ExternalCode = "";
                var hsje = "";
                var wsje = "";
                this.getSaleDeliveryList(outOrderCode, baseCode, ref sdId, ref ExternalCode, ref hsje, ref wsje);  //销货单主表

                var xhdzTable=GetSaleChilds(sdId,baseCode);//销货单子表
                var code = xhdzTable.Rows.Count;

                List<string> cmdlist = new List<string>();
        
                var totalHsJinE = 0m; //新含税金额（主表）
                var totalWsJinE = 0m; //新无税金额（主表）
                List<int> idlist = new List<int>();//本次修改的子表id

                foreach (DataRow r in teTable.Rows)
                {
                    #region
                    if (r["barStatus"].ToString() != "need-out")
                    {
                        rsl.Result = false;
                        rsl.Message = string.Format("此条码不允许出库，错误条码：{0}", r["barCode"].ToString());
                        txt.AddLogMsg(rsl.Message);
                        return rsl;
                    }

                    var dr = xhdzTable.Select("code='"+ r["proCode"].ToString() +"'");
                    if (dr.Length < 1)
                    {
                        rsl.Result = false;
                        rsl.Message = string.Format("存货错误：{0}", r["proCode"].ToString());
                        return rsl;
                    }
                    #endregion

                    bool isAdd = true;

                    var newQuantity = decimal.Parse(r["proWeight"].ToString()); //quantity 值要修改为 条码重量
                    var DetailMemo = r["barCode"].ToString(); //备注（出库条码）  

                    for (int x = 0; x < dr.Length; x++)
                    {
                        //遍历销货单
                        if (string.IsNullOrWhiteSpace(dr[x]["DetailMemo"].ToString()))
                        {
                            if (!idlist.Contains(int.Parse(dr[x]["id"].ToString())))
                            {
                                idlist.Add(int.Parse(dr[x]["id"].ToString()));
                                isAdd = false;  //修改

                                #region 销货单子表中字段备注为空 需要将重量 以及条码反写至重量、备注
                                //var quantity2 = decimal.Parse(dr[x]["quantity2"].ToString());//件数
                                var price = decimal.Parse(dr[x]["origDiscountPrice"].ToString()); //单价 （无税）  
                                var hsPrice = decimal.Parse(dr[x]["taxPrice"].ToString()); //含税单价     origTaxPrice 原币含税单价 , taxPrice 含税单价
                                var yws = decimal.Parse(dr[x]["origDiscountAmount"].ToString()); //原无税金额   
                                var yhs = decimal.Parse(dr[x]["taxAmount"].ToString()); //原含税金额     

                                var newHsJinE = newQuantity * hsPrice; //新含税金额  
                                var newWsJinE = newQuantity * price;   //新无税金额  
                                                                       //newWsJinE = Math.Round(newWsJinE,6);

                                //var unitExchangeRate = (newQuantity / quantity2).ToString("0.000000");

                                totalHsJinE = decimal.Parse(hsje) - yhs + newHsJinE;
                                totalWsJinE = decimal.Parse(wsje) - yhs + newWsJinE;


                                #region 修改的sql语句（修改）
                                sb.Clear();
                                sb.Append("update SA_SaleDelivery_b set quantity='" + newQuantity + "',quantity2='1',");
                                sb.Append("origDiscountAmount='" + newWsJinE + "',discountAmount='" + newWsJinE + "',");
                                sb.Append("taxAmount='" + newHsJinE + "',origTaxAmount='" + newHsJinE + "',unitExchangeRate='" + newQuantity + "',");
                                sb.Append("DetailMemo='" + DetailMemo + "' ");
                                sb.Append("where id ='" + dr[x]["id"].ToString() + "' ");
                                cmdlist.Add(sb.ToString());
                                #endregion

                                break;
                                #endregion
                            }

                        }
                    }
                    if (isAdd)
                    {
                        var newHsJinE = newQuantity * decimal.Parse(dr[0]["taxPrice"].ToString()); //新含税金额  
                        var newWsJinE = newQuantity * decimal.Parse(dr[0]["origDiscountPrice"].ToString());   //新无税金额  

                        //var unitExchangeRate = (newQuantity / decimal.Parse(dr[0]["quantity2"].ToString()) ).ToString("0.000000");

                        totalHsJinE = totalHsJinE + newHsJinE;
                        totalWsJinE = totalWsJinE + newWsJinE;

                        var newCode = code.ToString().PadLeft(4, '0');

                        #region  往销货单新建一行
                        sb.Clear();
                        sb.Append("insert into SA_SaleDelivery_b(");
                        sb.Append("code,");
                        sb.Append("quantity,quantity2,unitExchangeRate,baseQuantity,subQuantity,compositionQuantity,discountRate,origDiscountPrice,discountPrice,");
                        sb.Append("taxRate,");
                        sb.Append("origTaxPrice,taxPrice,origDiscountAmount,discountAmount,");
                        sb.Append("origTax,tax,");
                        sb.Append("origTaxAmount,taxAmount,");
                        sb.Append("costPrice,costAmount,isPresent,taxFlag,isManualCost,");
                        sb.Append("updatedBy,");
                        sb.Append("PriceStrategyTypeName,PriceStrategySchemeIds,PriceStrategySchemeNames,PromotionVoucherCodes,PromotionVoucherIds,IsMemberIntegral,IsPromotionPresent,");
                        sb.Append("PromotionSingleVoucherCode,idwarehouse,");
                        sb.Append("DetailMemo,idinventory,idbaseunit,idsubunit,idunit,idunit2,isSaleOut,PriceStrategyTypeId,idSaleDeliveryDTO,");
                        sb.Append("updated,LatestCost,LatestSaleOrigTaxPrice,SingleInvGrossProfit,GrossProfit,GrossProfitRate,");
                        sb.Append("DataSource,IsModifiedPrice,CostPriceGetType,RefundDifferenceFlag,");
                        sb.Append("PromotionBatchMemo,PromotionPresentBatchInfo,PromotionPresentBatchType,PromotionPriceBatchInfo, PromotionPriceBatchType,");
                        sb.Append("PreDiscountPrice,PreTaxPrice,");
                        sb.Append("DiscountPriceChange,TaxPriceChange,");
                        sb.Append("ExecutableQuantity,ExecutableQuantity2");
                        sb.Append(")");
                        sb.Append("select '" + newCode + "',");
                        sb.Append("'" + newQuantity + "','1','"+ newQuantity + "',baseQuantity,subQuantity,compositionQuantity,discountRate,origDiscountPrice,discountPrice,");
                        sb.Append("taxRate,");
                        sb.Append("origTaxPrice,taxPrice,'"+ newHsJinE + "','"+ newWsJinE + "',");
                        sb.Append("origTax,tax,");
                        sb.Append("'"+ newHsJinE + "','"+ newHsJinE + "',");
                        sb.Append("costPrice,costAmount,isPresent,taxFlag,isManualCost,");
                        sb.Append("updatedBy,");
                        sb.Append("PriceStrategyTypeName,PriceStrategySchemeIds,PriceStrategySchemeNames,PromotionVoucherCodes,PromotionVoucherIds,IsMemberIntegral,IsPromotionPresent,");
                        sb.Append("PromotionSingleVoucherCode,idwarehouse,");
                        sb.Append("'"+ DetailMemo + "',idinventory,idbaseunit,idsubunit,idunit,idunit2,isSaleOut,PriceStrategyTypeId,idSaleDeliveryDTO,");
                        sb.Append("updated,LatestCost,LatestSaleOrigTaxPrice,SingleInvGrossProfit,GrossProfit,GrossProfitRate,");
                        sb.Append("DataSource,IsModifiedPrice,CostPriceGetType,RefundDifferenceFlag,");
                        sb.Append("PromotionBatchMemo,PromotionPresentBatchInfo,PromotionPresentBatchType,PromotionPriceBatchInfo, PromotionPriceBatchType,");
                        sb.Append("PreDiscountPrice,PreTaxPrice,");
                        sb.Append("DiscountPriceChange,TaxPriceChange,");
                        sb.Append("ExecutableQuantity,ExecutableQuantity2 ");
                        sb.Append("from SA_SaleDelivery_b where id="+dr[0]["id"].ToString());
                        cmdlist.Add(sb.ToString()); 

                        code++;
                        #endregion
                    }

                    //#region 改变条码状态语句

                    //#endregion
                }

                #region 销货单主表信息修改
                sb.Clear();
                sb.Append("update SA_SaleDelivery set ExternalCode ='" + obj["tempCode"].ToString() + "',");
                sb.Append("origAmount ='" + totalWsJinE + "',amount ='" + totalWsJinE + "',");
                sb.Append("taxAmount ='" + totalHsJinE + "',origTaxAmount ='" + totalHsJinE + "' ");
                sb.Append("where code ='" + outOrderCode + "'");
                cmdlist.Add(sb.ToString());
                txt.AddLogMsg("销货单：" + outOrderCode +
                       "，出库前无税金额：" + wsje + ",出库后无税金额：" + totalWsJinE +
                       ",出库后无税金额：" + hsje + ",出库后含税金额：" + totalHsJinE);
                #endregion


                txt.AddLogMsg("执行语句数量："+cmdlist.Count.ToString());

                foreach (var s in cmdlist)
                {
                    txt.AddLogMsg(s);
                }

                rsl = cuHelper.TransUpdate(cmdlist,null,baseCode);

                #region 添加出入库记录
                List<OperateModel> list = new List<OperateModel>();
                if (rsl.Result)
                {
                    #region 构建参数数组
                    var cCode = getTimeString();//单据的临时编码
                    Dictionary<string, object> tempdic = new Dictionary<string, object>();
                    tempdic.Add("mCode", cCode);//临时编码
                    tempdic.Add("type", obj["inOutType"].ToString());
                    tempdic.Add("baseCode", obj["baseCode"].ToString());
                    #endregion
                    #region 添加主表和子表出入库记录
                    var tempbarCodes = string.Empty;//存入到出入库列表中的条码
                    insertMain(tempdic,teTable , outOrderCode, ref list);
                    rsl = insertList(tempdic, teTable, ref list,ref tempbarCodes, null);
                    if (!rsl.Result)
                    {
                        txt.AddLogMsg("添加出入库记录失败");
                        return rsl;
                    }
                    #endregion
                }
                else
                {
                    txt.AddLogMsg("出库失败:"+ rsl.Message);
                    return rsl;
                }
                #endregion

                #region 删除临时条码
                delteTempCode(teTable, ref list, obj["inOutType"].ToString());
                #endregion

                #region 执行修改语句
                rsl = cmd.MoreUpdate(list);
                if (!rsl.Result)
                {
                    var temRsl = rsl;
                    return temRsl;
                }
                #endregion
                rsl.Data = outOrderCode;
                rsl.Message = "出库成功";
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
                return rsl;
            }
            return rsl;
        }

        /// <summary>
        ///销货单主表信息
        /// </summary>
        private List<Dictionary<string, string>> getSaleDeliveryList(string cCode, string baseCode, ref string sdId,ref string ExternalCode,ref string hsje,ref string wsje)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from SA_SaleDelivery where code='" + cCode + "'");
            var sdList = cuHelper.getData(sb.ToString(), baseCode);
            if (sdList.Rows.Count > 0)
            {
                sdId = sdList.Rows[0]["id"].ToString();
                ExternalCode = sdList.Rows[0]["ExternalCode"].ToString();//扩展编码
                hsje = sdList.Rows[0]["taxAmount"].ToString();//含税金额
                wsje = sdList.Rows[0]["amount"].ToString();//无税金额
            }
            return cmd.TableToDictionary(sdList);
        }

       
        private List<Dictionary<string, string>> getSaleDelivery_dList(string dlid, string baseCode, string proCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select s.id,s.quantity,s.quantity2,s.DetailMemo,i.code,origDiscountPrice,taxPrice,origDiscountAmount,taxAmount ");
            sb.Append("from SA_SaleDelivery_b s inner join AA_InventoryEntity i on s.idinventory=i.id ");
            sb.Append("where idSaleDeliveryDTO='" + dlid + "' and i.code='" + proCode + "'");
            var dispatchList = cuHelper.getData(sb.ToString(), baseCode);
            return cmd.TableToDictionary(dispatchList);
        }

        /// <summary>
        /// 销货单子表信息
        /// </summary>
        /// <param name="dlid"></param>
        /// <param name="baseCode"></param>
        /// <param name="proCode"></param>
        /// <returns></returns>
        private DataTable GetSaleChilds(string dlid, string baseCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select s.id,s.quantity,s.quantity2,s.DetailMemo,i.code,origDiscountPrice,taxPrice,origDiscountAmount,taxAmount ");
            sb.Append("from SA_SaleDelivery_b s inner join AA_InventoryEntity i on s.idinventory=i.id ");
            sb.Append("where idSaleDeliveryDTO='" + dlid + "' ");
            return cuHelper.getData(sb.ToString(), baseCode);
        }
        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult updateUserPassword(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                #region 修改用户密码
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传递参数不允许为空";
                    return rsl;
                }
                #region 解密
                jsonStr = Encryption.DesDecrypt(jsonStr);
                #endregion
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                SysFrameWork.UserBLL userBLL = new SysFrameWork.UserBLL();
                var oldpwd = json["oldPassword"].ToString();
                var newpwd = json["newPassword"].ToString();
                string enpwd = Tools.Encryption.DesEncrypt(oldpwd);
                newpwd = Tools.Encryption.DesEncrypt(newpwd);
                string userCode = json["userCode"].ToString();
                string sql = "select * from sys_users_info where userCode='" + userCode + "'";
                var table = cmd.GetDataTable(sql);
                if (table.Rows.Count < 1)
                {
                    rsl.Message = "无法获取账号信息";
                    return rsl;
                }
                if (table.Rows[0]["userPwd"].ToString() != enpwd)
                {
                    rsl.Message = "当前密码输入错误";
                    return rsl;
                }
                sql = "update sys_users_info set userPwd='" + newpwd + "',openpwd='" + newpwd + "' where userCode='" + userCode + "'";
                rsl = cmd.UpdateSql(sql);
                #endregion
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
     
    }
}